package studentGUI.solver;

import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;

/**
 * Alternate Solver for XInteract using native compiler
 * and Java virtual machine.
 * 
 * @author conrada
 *
 */
public class SolverBytecode {

	// name (sans extension) for temporary source & bytecode
	private static final String tempFileLoc = "temp";
	// command to compile & execute bytecode
	private static final String compile = 
		"javac temp.java";
	private static final String run =
		"java temp";
	
	public static String interpret(String code) {
		
		try {
		
			// write the code to temp source file
			writeTempSource(code);
			
			// compile temp source to temp bytecode
			(new File(tempFileLoc+".class")).delete();
			Process codeRunner = Runtime.getRuntime().exec(compile);
			
			InputStream codeErrorReader = codeRunner.getErrorStream();
			
			Scanner codeErrorScanner = new Scanner(codeErrorReader);
			
			if (codeErrorScanner.hasNext()) {
				///* debug
				String error = "";
				while (codeErrorScanner.hasNext()) {
					error = error + codeErrorScanner.nextLine() + "\n";
				}
				System.out.println(error);
				//*/

				(new File(tempFileLoc+".java")).delete();
				(new File(tempFileLoc+".class")).delete();
				return "fail!";
			}
			
			// run the temp bytecode
			codeRunner = Runtime.getRuntime().exec(run);
			
			codeErrorReader = codeRunner.getErrorStream();
			
			codeErrorScanner = new Scanner(codeErrorReader);
			
			if (codeErrorScanner.hasNext()) {
				///* debug
				String error = "";
				while (codeErrorScanner.hasNext()) {
					error = error + codeErrorScanner.nextLine() + "\n";
				}
				System.out.println(error);
				//*/

				(new File(tempFileLoc+".java")).delete();
				(new File(tempFileLoc+".class")).delete();
				return "fail!";
			}

			(new File(tempFileLoc+".java")).delete();
			(new File(tempFileLoc+".class")).delete();
			return "pass!";
			
		} catch (IOException ex) {

		    ex.printStackTrace();
			(new File(tempFileLoc+".java")).delete();
			(new File(tempFileLoc+".class")).delete();
		    return "fail!";
				
		}
			
	}
	
	private static boolean writeTempSource(String code) {
		
		// delete source if it's already there
		(new File(tempFileLoc+".java")).delete();
		
		// write the code to the file
		try {
			
		    BufferedWriter out = new BufferedWriter(new FileWriter(tempFileLoc+".java"));
		    out.write(code);
		    out.close();
			return true;
		    
		} catch (IOException ex) {
			
		    ex.printStackTrace();
			return false;
		    
		}
		
	}
	
	/*
	 * this main is strictly for debugging
	 */
	public static void main(String[] args) {
		
		String sampleProg = "public class temp {" +
				"public static void main(String[] args){" +
				"System.out.println(\"Hello World\");" +
				"}" +
				"}";
		
		System.out.print(interpret(sampleProg));	
		
	}
	
}
